import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
// 把本地数据拿出来赋值给 state 里面的 cart
let localStorageCart
if (localStorage.cart === undefined) {
  localStorageCart = []
} else {
  localStorageCart = JSON.parse(localStorage.cart)
}

export default new Vuex.Store({
  state: {
    cart: localStorageCart,// 存储商品信息 selected,用户选中的商品
  },
  mutations: {
    addCart(state, goodsList) {
      // 点击加入购物车，信息保存到 state 的 cart 上
      let flag = false // 默认认为没有找到,如果找到就改数量，没有找到就重新添加
      state.cart.some(item => {
        if (item.id == goodsList.id) {
          item.count += parseInt(goodsList.count)
          flag = true
          return true
        }
      })
      if (!flag) {
        state.cart.push(goodsList)
      }
      // 当更新 cart 把值放到本地存储 localStorage 里面
      localStorage.cart = JSON.stringify(state.cart)
    },
    updateGoodsCount(state, goodsCount) {
      // 修改数量
      state.cart.some(item => {
        if (item.id == goodsCount.id) {
          item.count = parseInt(goodsCount.count)
          return true
        }
      })
      // 修改完商品数量，保存到 localStorage 里面
      localStorage.cart = JSON.stringify(state.cart)
    },
    removeIdCart(state, id) {
      // 根据 id 删除 state 里面的商品信息
      state.cart.some((item, i) => {
        if(item.id == id) {
          state.cart.splice(i, 1)
          return true
        }
      })
      // 删除完商品数量，保存到 localStorage 里面
      localStorage.cart = JSON.stringify(state.cart)
    },
    updateGoodsSelected(state, info) {
      state.cart.some(item => {
        if(item.id == info.id) {
          item.selected = info.selected
        }
      })
      // 修改选中商品，保存到 localStorage 里面
      localStorage.cart = JSON.stringify(state.cart)
    }
  },
  getters: {
    getAllCount(state) {
      let allCount = 0
      state.cart.forEach(item => {
        allCount += item.count
      })
      return allCount
    },
    getGoodsCount(state) {
      let goodsCount = {}
      state.cart.forEach(item => {
        goodsCount[item.id] = item.count
      })
      return goodsCount
    },
    getGoodsSelect(state) {
      let goodsSelect = {}
      state.cart.some(item => {
        goodsSelect[item.id] = item.selected
      })
      return goodsSelect
    },
    getGoodsSelectCount(state) {
      let goodsCountPrice = { count: 0, price:0 }
      state.cart.forEach(item => {
        if(item.selected) {
          goodsCountPrice.count += item.count
          goodsCountPrice.price += item.price * item.count
        }
      })
      return goodsCountPrice
    }
  },
  actions: {}
});
